package com.lyc.lojbackendquestionservice.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyc.lojbackendcommon.common.ErrorCode;
import com.lyc.lojbackendcommon.constant.CommonConstant;
import com.lyc.lojbackendcommon.exception.BusinessException;
import com.lyc.lojbackendcommon.utils.SqlUtils;
import com.lyc.lojbackendmodel.model.codesandbox.JudgeInfo;
import com.lyc.lojbackendmodel.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.lyc.lojbackendmodel.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.lyc.lojbackendmodel.model.dto.questionsubmit.QuestionSubmitTestRequest;
import com.lyc.lojbackendmodel.model.entity.Question;
import com.lyc.lojbackendmodel.model.entity.QuestionSubmit;
import com.lyc.lojbackendmodel.model.entity.User;
import com.lyc.lojbackendmodel.model.enums.QuestionSubmitLanguageEnum;
import com.lyc.lojbackendmodel.model.enums.QuestionSubmitStatusEnum;
import com.lyc.lojbackendmodel.model.vo.QuestionSubmitVO;
import com.lyc.lojbackendquestionservice.mapper.QuestionSubmitMapper;
import com.lyc.lojbackendquestionservice.rabbitmq.MyMessageProducer;
import com.lyc.lojbackendquestionservice.service.QuestionService;
import com.lyc.lojbackendquestionservice.service.QuestionSubmitService;
import com.lyc.lojbackendserviceclient.service.JudgeFeignClient;
import com.lyc.lojbackendserviceclient.service.UserFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import static com.lyc.lojbackendcommon.config.RabbitmqConfig.EXCHANGE_CODE;
import static com.lyc.lojbackendcommon.config.RabbitmqConfig.ROUTINGKEY_CODE;

/**
 * @author Linyichengzi
 * @description 针对表【question_submit(题目提交)】的数据库操作Service实现
 * @createDate 2023-08-10 10:29:26
 */
@Service
@Slf4j
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserFeignClient userFeignClient;

    @Resource
    private JudgeFeignClient judgeFeignClient;
    
    @Resource
    private MyMessageProducer myMessageProducer;

    /**
     * 提交题目
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    @Transactional
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (languageEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }
        Long questionId = questionSubmitAddRequest.getQuestionId();
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 题目提交数增加
        synchronized (question) {
            LambdaUpdateWrapper<Question> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(Question::getId, questionId);
            lambdaUpdateWrapper.setSql("submitNum = submitNum + 1");
            boolean update = questionService.update(lambdaUpdateWrapper);
            if(!update) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "数据保存失败");
            }
        }
        // 是否已提交题目
        long userId = loginUser.getId();
        // 每个用户串行提交题目
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(language);
        //设置初始状态
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
        }
        // 执行判题服务
        Long questionSubmitId = questionSubmit.getId();
        // 消息队列执行
        myMessageProducer.sendMessage(EXCHANGE_CODE, ROUTINGKEY_CODE, String.valueOf(questionSubmitId));
        return questionSubmitId;
//        judgeFeignClient.doJudge(questionSubmitId);

        // 3种方法执行判题
/*        // 方法1、消息队列处理，发送消息
        myMessageProducer.sendMessage(EXCHANGE_CODE, ROUTINGKEY_CODE, String.valueOf(questionSubmitId));        
        
         // 方法2、异步执行判题
        CompletableFuture.runAsync(() -> {
            judgeFeignClient.doJudge(questionSubmitId);
        });

        // 方法3、同步执行判题
        judgeFeignClient.doJudge(questionSubmitId);*/

        // 计算同步执行判题所需时间
/*        // 同步执行判题计时开始
        long startTimeSync = System.nanoTime();
        // 同步执行判题
        judgeFeignClient.doJudge(questionSubmitId);
        // 同步执行判题计时结束
        long endTimeSync = System.nanoTime();
        // 计算同步执行判题的耗时（以纳秒为单位）
        long executionTimeSyncNano = endTimeSync - startTimeSync;
        double executionTimeSyncMillis = executionTimeSyncNano / 1e6; // 转换为毫秒
        System.out.println("同步执行判题耗时: " + executionTimeSyncMillis + " 毫秒");*/

        // 计算异步执行判题所需时间
/*
        // 异步执行判题计时开始
        long startTimeAsync = System.nanoTime();
        // 异步执行判题
        CompletableFuture<Void> asyncFuture = CompletableFuture.runAsync(() -> {
            judgeFeignClient.doJudge(questionSubmitId);
        });
        asyncFuture.join(); // 等待异步操作完成
        // 异步执行判题计时结束
        long endTimeAsync = System.nanoTime();
        // 计算异步执行判题的耗时（以纳秒为单位）
        long executionTimeAsyncNano = endTimeAsync - startTimeAsync;
        double executionTimeAsyncMillis = executionTimeAsyncNano / 1e6; // 转换为毫秒
        System.out.println("异步执行判题耗时: " + executionTimeAsyncMillis + " 毫秒");
*/
        
    }

    /**
     * 提交题目测试
     * @param questionSubmitTestRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmitTest(QuestionSubmitTestRequest questionSubmitTestRequest, User loginUser) {
        //校验编程语言是否合法
        String language = questionSubmitTestRequest.getLanguage();
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (languageEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言错误");
        }
        Long questionId = questionSubmitTestRequest.getQuestionId();
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已提交题目
        long userId = loginUser.getId();
        // 每个用户串行提交题目
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(questionSubmitTestRequest.getCode());
        questionSubmit.setLanguage(language);
        //设置初始状态
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");
        // 设置人工测评为 1
        questionSubmit.setIsManual(1);
        // 设置题目提交的测试用例
//        log.info("测试数据" + questionSubmitTestRequest.getInput());
        questionSubmit.setTestCase(questionSubmitTestRequest.getInput());
        boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
        }
        // 执行判题服务
        Long questionSubmitId = questionSubmit.getId();
        // 消息队列执行
//        myMessageProducer.sendMessage(EXCHANGE_CODE, ROUTINGKEY_CODE, String.valueOf(questionSubmitId));
        judgeFeignClient.doJudge(questionSubmitId);
        return questionSubmitId;
    }

    /**
     * 获取查询包装类（用户根据哪些字段去查询，根据前端传来的请求对象，得到mybatis框架支持的查询 QueryWrapper 类）
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        Long userId = questionSubmitQueryRequest.getUserId();
        String userName = questionSubmitQueryRequest.getUserName();
        if(userName != null) {
            User user = userFeignClient.getByUserName(userName);
            if(user != null) {
                userId = user.getId();
            }else {
                userId = 0L;
            }
        }
        
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        
        //这两个是排序的，通过继承得到的属性
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        // 添加查询条件 添加判断是否是人工测试
        queryWrapper.eq("isManual",0);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_QUESTION_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取单个题目提交信息封装类
     *
     * @param questionSubmit
     * @param loginUser
     * @return
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        //脱敏，仅本人和管理员能看见自己（提交userId 和登陆用户id不同）提交的代码
        Long loginUserId = loginUser.getId();
        Long questionId = questionSubmit.getQuestionId();
        Long userId = questionSubmit.getUserId();
        User user = userFeignClient.getById(userId);
        String userName = user.getUserName();
        questionSubmitVO.setUserName(userName);
        Question question = questionService.getById(questionId);
        String title = question.getTitle();
        questionSubmitVO.setTitle(title);
        String judgeInfoStr = questionSubmit.getJudgeInfo();
        JudgeInfo judgeInfo = JSONUtil.toBean(judgeInfoStr, JudgeInfo.class);
        questionSubmitVO.setMessage(judgeInfo.getMessage());
        questionSubmitVO.setTime(judgeInfo.getTime());
        questionSubmitVO.setMemory(judgeInfo.getMemory());
        if (!Objects.equals(loginUserId, userId) && !userFeignClient.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
        
    }

    /**
     * 脱敏题目提交信息
     *
     * @param questionSubmitPage
     * @param loginUser
     * @return
     */
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        // 填充信息
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }
    
}




